﻿using CastingWellEquipmentGUI.Dao;
using CastingWellEquipmentGUI.Model;
using CastingWellEquipmentGUI.Utils;
using CastingWellEquipmentGUI.ViewModel.Common.Command;
using CastingWellEquipmentGUI.ViewModel.Common.WindowsManager;
using GalaSoft.MvvmLight;
using GalaSoft.MvvmLight.Messaging;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;

namespace CastingWellEquipmentGUI.ViewModel.Pages.SettingMenuPages
{
    public class ControlTagSettingPageViewModel : ViewModelBase
    {

        /// <summary>
        /// 搜索条件
        /// </summary>
        private Meta_Tag _SeachModel = new Meta_Tag();
        /// <summary>
        /// 搜索条件
        /// </summary>
        public Meta_Tag SeachModel
        {
            get { return _SeachModel; }
            set { _SeachModel = value; }
        }

        private ObservableCollection<ControlTag> _PlcModels;

        public ObservableCollection<ControlTag> PlcModels
        {
            get { return _PlcModels; }
            set
            {
                _PlcModels = value;

                RaisePropertyChanged("PlcModels");
            }
        }
        /// <summary>
        /// 选中的PLC项目
        /// </summary>
        private ControlTag _SelectPlcModel;
        /// <summary>
        /// 选中的PLC项目
        /// </summary>
        public ControlTag SelectPlcModel
        {
            get { return _SelectPlcModel; }
            set
            {
                _SelectPlcModel = value;
                if (_SelectPlcModel != null)
                {
                    RefreshTagModels();
                }
                RaisePropertyChanged("SelectPlcModel");
            }
        }

        private ObservableCollection<ControlTag> _TagModels;

        public ObservableCollection<ControlTag> TagModels
        {
            get { return _TagModels; }
            set
            {
                _TagModels = value;
                RaisePropertyChanged("TagModels");
            }
        }
        /// <summary>
        /// 选中的PLC项目
        /// </summary>
        private ControlTag _SelectTagModel;
        /// <summary>
        /// 选中的PLC项目
        /// </summary>
        public ControlTag SelectTagModel
        {
            get { return _SelectTagModel; }
            set
            {
                _SelectTagModel = value;
                RaisePropertyChanged("SelectTagModel");
            }
        }
        #region 分页使用
        /// <summary>
        /// 每页数量
        /// </summary>
        private int itemCount = 10;
        /// <summary>
        /// 总数量
        /// </summary>
        private int totalDataCount = 0;
        /// <summary>
        /// 总页数
        /// </summary>
        public int TotalPageNumber
        {
            get
            {
                int totalPageNumber = totalDataCount / itemCount;
                if (totalDataCount % itemCount > 0)
                {
                    totalPageNumber++;
                }
                return totalPageNumber;

            }
        }
        /// <summary>
        /// 总数据量
        /// </summary>
        public int TotalDataCount
        {
            get { return totalDataCount; }
            set
            {
                totalDataCount = value;
                RaisePropertyChanged("TotalDataCount");
                RaisePropertyChanged("TotalPageNumber");
            }
        }
        /// <summary>
        /// 当前所在页数
        /// </summary>
        private int _CurrentPageNumber = 1;
        /// <summary>
        /// 当前所在页数
        /// </summary>
        public int CurrentPageNumber
        {
            get { return _CurrentPageNumber; }
            set
            {
                _CurrentPageNumber = value;
                RaisePropertyChanged("CurrentPageNumber");
            }
        }
        /// <summary>
        /// 上一页页数
        /// </summary>
        public int PreviousPageNumber
        {
            get
            {
                if (_CurrentPageNumber - 1 > 0)
                {
                    return _CurrentPageNumber - 1;
                }
                return 1;
            }

        }
        /// <summary>
        /// 下一页页数
        /// </summary>
        public int NextPageNumber
        {
            get
            {
                if (_CurrentPageNumber + 1 <= TotalPageNumber)
                {
                    return _CurrentPageNumber + 1;
                }
                return _CurrentPageNumber;
            }

        }
        /// <summary>
        /// 选中的项目
        /// </summary>
        private ControlTag _SelectedItemModel;
        /// <summary>
        /// 选中的项目
        /// </summary>
        public ControlTag SelectedItemModel
        {
            get { return _SelectedItemModel; }
            set
            {
                _SelectedItemModel = value;

                RaisePropertyChanged("SelectedItemModel");
            }
        }
        /// <summary>
        /// 分页页码集合
        /// </summary>
        private ObservableCollection<PageNumerModel> _PageNumers = new ObservableCollection<PageNumerModel>();
        /// <summary>
        /// 分页页码集合
        /// </summary>
        public ObservableCollection<PageNumerModel> PageNumers
        {
            get => _PageNumers;
            set
            {
                _PageNumers = value;
                RaisePropertyChanged("PageNumers");
            }
        }
        /// <summary>
        /// 跳转到指定页面命令
        /// </summary>
        public DelegateCommand GoToPageByNumberCommand { get; set; }
        /// <summary>
        /// 跳转到指定页面并关闭AllPageNumberPanel窗体命令
        /// </summary>
        public DelegateCommand GoToPageByNumberAndCloseAllPageNumberPanelCommand { get; set; }
        #endregion 分页使用
        public DelegateCommand SaveAndHideCommand { get; set; }
        public DelegateCommand ShowEditModelCommand { get; set; }
        public DelegateCommand HideControlTagEditWindowCommand { get; set; }
        public DelegateCommand SearchCommand { get; set; }
        /// <summary>
        /// 主列表数据
        /// </summary>
        private ObservableCollection<ControlTag> _DataCollection;
        /// <summary>
        /// 主列表数据
        /// </summary>
        public ObservableCollection<ControlTag> DataCollection
        {
            get { return _DataCollection; }
            set
            {
                _DataCollection = value;
                RaisePropertyChanged("DataCollection");
            }
        }
        public ControlTagSettingPageViewModel()
        {
            InitPlcModels();
            InitDataCollection();
            GoToPageByNumberCommand = new DelegateCommand()
            {
                ExecuteActionObj = new Action<object>(GoToPageByNumberHandler)
            };
            GoToPageByNumberAndCloseAllPageNumberPanelCommand = new DelegateCommand()
            {
                ExecuteActionObj = new Action<object>(GoToPageByNumberAndCloseAllPageNumberPanelHandler)
            };
            ShowEditModelCommand = new DelegateCommand()
            {
                ExecuteActionObj = new Action<object>(ShowEditModelHandler)
            };
            HideControlTagEditWindowCommand = new DelegateCommand()
            {
                ExecuteActionObj = new Action<object>(HideControlTagEditWindowHandler)
            };
            SaveAndHideCommand = new DelegateCommand()
            {
                ExecuteActionObj = new Action<object>(SaveAndHideHandler)
            };
            SearchCommand = new DelegateCommand()
            {
                ExecuteActionObj = new Action<object>(SearchHandler)
            };
        }

        public void SearchHandler(object obj)
        {
            RefreshTagModels();
        }
        private void SaveAndHideHandler(object obj)
        {
            ControlTag QueryModel = new ControlTag
            {
                ControlId = SelectedItemModel.ControlId,
                TagID = SelectTagModel.TagID
            };
            string sql = @" SELECT ControlId,
                                   TagInfoId AS TagID
                            FROM ControlAndTagInfo 
                            WHERE ControlId = @ControlId";
            ControlTag QueryResult = DapperToolsThisSystem.Query<ControlTag>(sql, QueryModel);
            if (QueryResult == null)
            {
                sql = @"INSERT INTO ControlAndTagInfo (ControlId,TagInfoId,RelationType)
                        VALUES(@ControlId,@TagID,1)";
                DapperToolsThisSystem.Add<ControlTag>(sql, QueryModel);
            }
            else
            {
                sql = @"UPDATE ControlAndTagInfo 
                        SET ControlId = @ControlId,
                            TagInfoId = @TagID
                        WHERE ControlId = @ControlId";
                DapperToolsThisSystem.Update<ControlTag>(sql, QueryModel);
            }
            InitDataCollection();
            Messenger.Default.Send<NotificationMessage>(new NotificationMessage(this, "HideControlTagEditWindow"));
        }
        private void HideControlTagEditWindowHandler(object obj)
        {
            Messenger.Default.Send<NotificationMessage>(new NotificationMessage(this, "HideControlTagEditWindow"));
        }
        private void ShowEditModelHandler(object obj)
        {
            if (SelectedItemModel != null)
            {
                SelectPlcModel = null;
                for (int i = 0; i < PlcModels.Count; i++)
                {
                    if (PlcModels[i].BrandName == SelectedItemModel.BrandName &&
                        PlcModels[i].PlcModelName == SelectedItemModel.PlcModelName)
                    {
                        SelectPlcModel = PlcModels[i];
                        break;
                    }
                }
                if (SelectPlcModel==null)
                {
                    SelectPlcModel = PlcModels[0];
                }
                RefreshTagModels();
                WindowManager.ShowDialog("ControlTagEditWindow", null);
            }
            else
            {
                MessageBox.Show("请选择要编辑的控件！");
            }

        }
        private void RefreshTagModels()
        {
            string sql = @"SELECT 
                            Meta_Tag.TagID,
                            Meta_Tag.TagName,
                            Meta_Tag.Address, 
                            Meta_Tag.DataType
                           FROM DB_AlarmServer.dbo.Meta_Tag 
                           INNER JOIN DB_AlarmServer.dbo.Meta_Group ON Meta_Tag.GroupID = Meta_Group.GroupID
                           INNER JOIN DB_AlarmServer.dbo.Meta_Driver ON Meta_Driver.DriverID = Meta_Group.DriverID 
                           INNER JOIN DB_AlarmServer.dbo.PlcModel ON PlcModel.PlcModelId = Meta_Driver.PlcModelId 
                           INNER JOIN DB_AlarmServer.dbo.Brand ON Brand.BrandId = PlcModel.BrandId 
                           WHERE PlcModel.PlcModelName = '" + SelectPlcModel.PlcModelName + @"' 
                           AND Brand.BrandName = '" + SelectPlcModel.BrandName + @"'";
            if (SeachModel.TagName != null && SeachModel.TagName != "" && !XyhUtils.IsHasSQLInject(SeachModel.TagName))
            {
                sql += @" AND Meta_Tag.TagName LIKE '%" + SeachModel.TagName + "%'";
            }
            if (SeachModel.Address != null && SeachModel.Address != "" && !XyhUtils.IsHasSQLInject(SeachModel.Address))
            {
                sql += @" AND Meta_Tag.Address LIKE '%" + SeachModel.Address + "%'";
            }
            sql += @" ORDER BY Meta_Tag.TagName";
            TagModels = DapperToolsThisSystem.QueryOc<ControlTag>(sql);
            for (int i = 0; i < TagModels.Count; i++)
            {
                if (TagModels[i].TagID == SelectedItemModel.TagID)
                {
                    SelectTagModel = TagModels[i];
                    break;
                }
            }
        }


        private void InitPlcModels()
        {
            PlcModels = DapperToolsThisSystem.QueryOc<ControlTag>("SELECT Brand.BrandName,PlcModel.PlcModelName FROM DB_AlarmServer.dbo.PlcModel LEFT JOIN DB_AlarmServer.dbo.Brand ON PlcModel.BrandId = Brand.BrandId ORDER BY Brand.BrandId");
        }

        /// <summary>
        /// 跳转到指定页面命令的处理器
        /// </summary>
        /// <param name="obj"></param>
        private void GoToPageByNumberHandler(object obj)
        {
            switch (obj.ToString())
            {
                case "PreviousPage":
                    CurrentPageNumber = PreviousPageNumber;
                    break;
                case "NextPage":
                    CurrentPageNumber = NextPageNumber;
                    break;
                case "FirstPage":
                    CurrentPageNumber = 1;
                    break;
                case "LastPage":
                    CurrentPageNumber = TotalPageNumber;
                    break;
                default:
                    CurrentPageNumber = int.Parse(obj.ToString());
                    break;
            }
            InitDataCollection();
        }
        /// <summary>
        /// 跳转到更改页码的列表
        /// </summary>
        /// <param name="obj"></param>
        private void GoToPageByNumberAndCloseAllPageNumberPanelHandler(object obj)
        {
            GoToPageByNumberHandler(obj);
            Messenger.Default.Send<NotificationMessage>(new NotificationMessage(this, "HideAllPageNumberPanelForRecipeManage"));
        }
        /// <summary>
        /// 初始化主列表数据
        /// </summary>
        private void InitDataCollection()
        {
            string baseSearchSql = @"SELECT ROW_NUMBER() OVER (
                                                                ORDER BY Form.FormId
                                                               ) as rownumber,
                                            Form.FormId,
                                            Form.FormExplain,
                                            Control.ControlId,
                                            Control.ControlExplain,
                                            Meta_Tag.TagID,
                                            Meta_Tag.TagName,
                                            Meta_Tag.Address,
                                            PlcModel.PlcModelName,
                                            Brand.BrandName
                                            from DB_CWEGUI.dbo.Form 
                                            LEFT JOIN DB_CWEGUI.dbo.Control ON Control.FormId = Form.FormId
                                            LEFT JOIN DB_CWEGUI.dbo.ControlAndTagInfo ON ControlAndTagInfo.ControlId = Control.ControlId
                                            LEFT JOIN DB_AlarmServer.dbo.Meta_Tag ON Meta_Tag.TagID = ControlAndTagInfo.TagInfoId
                                            LEFT JOIN DB_AlarmServer.dbo.Meta_Group ON Meta_Group.GroupID = Meta_Tag.GroupID
                                            LEFT JOIN DB_AlarmServer.dbo.Meta_Driver ON Meta_Driver.DriverID = Meta_Group.DriverID
                                            LEFT JOIN DB_AlarmServer.dbo.PlcModel ON PlcModel.PlcModelId = Meta_Driver.PlcModelId
                                            LEFT JOIN DB_AlarmServer.dbo.Brand ON Brand.BrandId = PlcModel.BrandId WHERE 1 = 1 ";

            string pageingSql = @"SELECT TOP " + itemCount + @" * 
                                  FROM (" + baseSearchSql + @") temp_row
                                  WHERE rownumber > ((" + CurrentPageNumber + @" - 1 ) * " + itemCount + @" ); ";
            DataCollection = DapperToolsThisSystem.QueryOc<ControlTag>(pageingSql);
            //总数据量
            TotalDataCount = DapperToolsThisSystem.GetCount(baseSearchSql);
            for (int i = 0; i < DataCollection.Count; i++)
            {
                DataCollection[i].OrderNo = (i + 1 + ((CurrentPageNumber - 1) * itemCount));
            }
        }
    }
}
